// const { uploadFile } = require("wx-server-sdk");

// miniprogram/pages/post/index.js
const db = wx.cloud.database()
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    areaList: [
      { text: '全部', value: 0 },
      { text: '学习交流', value: 1 },
      { text: '生活分享', value: 2 },
      { text: '表白墙', value: 3 },
      { text: 'ACG', value: 4 },
    ],
    selected: 0,
    imgPaths: [],
    imgPaths_up:[],
    imgcount:0,
    title:'',
    content:'',
    imgR:true//默认图片合法
  },
  changeSection(e)
  {
    console.log(e.detail)
    this.setData({
      selected:e.detail
    })
  },

  inputTitle:function(e){
    this.setData({
      title:e.detail.value
    })
  },
  inputContent:function(e){
    this.setData({
      content:e.detail.value
    })
  },
  //发布
  pulish(){   
    var that=this
    if(this.data.title.length==0 || this.data.content.length==0){
      wx.showToast({
        icon:'none',
        title: '请输入标题及内容',
      })
    }
    else if(that.data.imgR==false){
      wx.showToast({
        icon:'error',
        title: '图片不合法',
      })
    }
    else{
      wx.showLoading({
            title: '上传中',
            showCancel: true,
            icon:'loading',
            mask:true
          })

      wx.cloud.callFunction({
        name: 'contentCheck',
        data: {
          msg: that.data.title+that.data.content,
        },
        success(res) {
          console.log(res.result)
          if (res.result.errCode == 87014) {
            wx.showToast({
              title: '文字违规',
              icon:'error'
            })
          }
          else{
            if(that.data.imgPaths.length==0){
              var data = {
                imgPaths: that.data.imgPaths_up, //将图片储存为数组类型
                title:that.data.title,
                tContent: that.data.content, //用户输入的文字
                // uID: wx.getStorageSync('userId'),
                sID:[that.data.areaList[that.data.selected].text].concat("全部"),
                topicReplyCount: 0,
                tTime: Date.parse(new Date())/1000,
                lastReplytime:Date.parse(new Date())/1000,
                uName:app.globalData.uName,
                head_pic:app.globalData.head_pic
            }
            db.collection("topic").add({
              data:data,
              success:res=>{
                wx.hideLoading()
                wx.showToast({
                  title: '上传成功',
                })
        
              },
              fail:e=>{
                wx.showToast({
                  title: '发布错误',
                })
                console.log(e)
              },
              complete: () => {    
                setTimeout(function(){
                  wx.reLaunch({
                    url: '../forum/index',
                  })
                },1000)
              } 
            })



            }
            else{
              for(var i=0,h=that.data.imgPaths.length;i<h;i++){

                const  filePath  = that.data.imgPaths[i]
                const cloudPath = Math.random()*100000 + filePath.match(/\.[^.]+?$/)[0]
      
                wx.cloud.uploadFile({
                  cloudPath,
                  filePath,
                  success: res => {
                    that.setData({
                    imgPaths_up:that.data.imgPaths_up.concat(res.fileID),
                    imgcount:that.data.imgcount+1
                    })
                    if(that.data.imgcount==that.data.imgPaths.length){
                      var data = {
                        imgPaths: that.data.imgPaths_up, //将图片储存为数组类型
                        title:that.data.title,
                        tContent: that.data.content, //用户输入的文字
                        // uID: wx.getStorageSync('userId'),
                        sID:[that.data.areaList[that.data.selected].text].concat("全部"),
                        topicReplyCount: 0,
                        tTime: Date.parse(new Date())/1000,
                        lastReplytime:Date.parse(new Date())/1000,
                        uName:app.globalData.uName,
                        head_pic:app.globalData.head_pic
                      }
                      console.log(data);
                      db.collection("topic").add({
                        data:data,
                        success:res=>{
                          wx.hideLoading()
                          wx.showToast({
                            title: '上传成功',
                          })
                  
                        },
                        fail:e=>{
                          wx.showToast({
                            title: '发布错误',
                          })
                          console.log(e)
                        },
                        complete: () => {    
                          setTimeout(function(){
                            wx.reLaunch({
                              url: '../forum/index',
                            })
                          },1000)
                        } 
                      })
                    }
                  }
                })
              }

            }
           
          }
        }
      })
    }
 
  },

  // 处理图片上传
  handleUpdate(){
    var that=this
    // 调chooseImage
    wx.chooseImage({
      count: 6,
      sizeType: ['compressed'],
      sourceType: ['album'],
      
      success: function (res) {
        var imgpath=res.tempFilePaths
        that.setData({
          imgPaths:res.tempFilePaths
        })
        for(var i=0,h=imgpath.length;i<h;i++){
            wx.cloud.callFunction({
              name: 'contentCheck',
              data: {
                img: imgpath[i]
              },
              success(res) {
                console.log(res.result)
                if(res.result.imageR.errCode == 87014){
                  wx.showToast({
                    icon:'error',
                    title: '图片违规',
                  })
                  that.setData({
                    imgR:false//图片不合法
                  })
                }  
              }
            })
      }
    }
    })
  
},

  //删除图片
  handleDelImg:function(e){
    var that = this;
    var images = that.data.imgPaths;
    var index = e.currentTarget.dataset.index;//获取当前长按图片下标
    wx.showModal({
     title: '提示',
     content: '确定要删除此图片吗？',
     success: function (res) {
      if (res.confirm) {
       console.log('点击确定了');
       images.splice(index, 1);
      } else if (res.cancel) {
        console.log('点击取消了');
        return false;    
       }
      that.setData({
        imgPaths:images
      });
     }
    })
  },
  previewImg: function (e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    var imgs = this.data.imgPaths;
    console.log(index,imgs);
    wx.previewImage({
    //当前显示图片
    current: imgs[index],
    //所有图片
    urls: imgs
    })
   },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(app.globalData.uName,app.globalData.head_pic);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})